package qj.app.console.invoker;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import qj.app.console.ConsoleMain;
import qj.app.console.Exec;
import qj.util.FileUtil;
import qj.util.IOUtil;
import qj.util.LangUtil;
import qj.util.ProcessUtil;
import qj.util.SystemUtil;
import qj.util.funct.F0;
import qj.util.funct.P0;
import qj.util.funct.P1;

public class JBossInvoker extends AbstractInvoker {

	private F0<String> homeF = new F0<String>() {public String e() {
		return config.get("jboss.home");
	}};
	
	public void start() {
		P1<String> normalOut = ta.createNormalOut();
		P1<String> errOut = ta.createErrOut();

//		new File(homeF.e() + "/bin/wrapperCommands.txt").delete();
		ta.setText("");
		try {

//			String classpathSeparator = SystemUtil.classpathSeparator();
//			String cp = SystemUtil.jdkHome() + "/lib/tools.jar" + classpathSeparator + homeF.e() + "/bin/run.jar" + classpathSeparator;
//			String args = "-Dprogram.name=run.bat -server -Xms128m -Xmx512m -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000    -Djava.endorsed.dirs=\""+ homeF.e() + "/lib/endorsed\"";
//			Process p = Runtime.getRuntime().exec(
//					"java " + args + " -cp \"" + cp + 
//					SystemUtil.classPaths() + "\" " + Exec.class.getName() + 
//					" org.jboss.Main",null,new File(homeF.e() + "/bin"));
			
			Process p = Runtime.getRuntime().exec(
					"cmd /c run.bat",null,new File(homeF.e() + "/bin"));
			
			final OutputStream outputStream = p.getOutputStream();
			P1<String> observeP1 = ConsoleMain.observeP1(normalOut, "Press any key to continue .", new P0() {public void e() {
				try {
					outputStream.write('\n');
					outputStream.flush();
				} catch (IOException e1) {
					throw new RuntimeException(e1);
				}
			}});
			
			IOUtil.readInputStreamToP1(p.getInputStream(), observeP1);
			IOUtil.readInputStreamToP1(p.getErrorStream(), errOut);
			
			onStart.e();
			ProcessUtil.onExit(p, new P0() {public void e() {
				onStop.e();
			}});
		} catch (IOException e1) {
			errOut.e(LangUtil.getStackTrace(e1));
		}
	}

	@Override
	public void stop() {
//		FileUtil.writeToFile("exit", new File(homeF.e() + "/bin/wrapperCommands.txt"));
		try {
			Runtime.getRuntime().exec(
						"cmd /c shutdown.bat -S",null,new File(homeF.e() + "/bin"));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	

//	JButton btnClean = btn("Clean", new P0() {public void e() {
//		new File(appHomeF.e() + "/WEB-INF/appengine-generated/local_db.bin").delete();
//	}});
}
